package com.zhijian.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhijian.entity.Note;
import com.zhijian.entity.NoteComment;
import com.zhijian.entity.R;
import com.zhijian.entity.WxUserInfo;
import com.zhijian.service.INoteService;
import com.zhijian.service.INoteCommentService;
import com.zhijian.service.IWxUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.text.SimpleDateFormat;

@RestController
@RequestMapping("/note")
public class NoteController {

    private static final Logger log = LoggerFactory.getLogger(NoteController.class);

    @Autowired
    private INoteService noteService;
    
    @Autowired
    private INoteCommentService noteCommentService;

    @Autowired
    private IWxUserInfoService wxUserInfoService;

    /**
     * 获取笔记列表
     */
    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") Integer pageNum,
                 @RequestParam(defaultValue = "10") Integer pageSize,
                 @RequestParam(required = false) String keyword) {
        Page<Note> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Note> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("title", keyword)
                .or()
                .like("content", keyword));
        }
        
        queryWrapper.orderByDesc("createTime");
        Page<Note> page1 = noteService.page(page, queryWrapper);
        page1.getRecords().forEach(note -> {
            WxUserInfo wxUserInfo = wxUserInfoService.getById(note.getUserId());
            note.setWxUserInfo(wxUserInfo);
        });
        return R.ok().put("data", page1);
    }

    /**
     * 获取笔记详情
     */
    @GetMapping("/detail/{id}")
    public R detail(@PathVariable Integer id) {
        Note note = noteService.getById(id);
        if (note == null) {
            return R.error("笔记不存在");
        }
        // 增加浏览量
        note.setViews(note.getViews() + 1);
        noteService.updateById(note);
        WxUserInfo wxUserInfo = wxUserInfoService.getById(note.getUserId());
        note.setWxUserInfo(wxUserInfo);


        return R.ok().put("data", note);
    }

    /**
     * 获取笔记评论
     */
    @GetMapping("/comments/{noteId}")
    public R comments(@PathVariable Integer noteId) {
        QueryWrapper<NoteComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("noteId", noteId)
                   .orderByDesc("createTime");
        List<NoteComment> list = noteCommentService.list(queryWrapper);
        list.forEach(noteComment -> {
            WxUserInfo wxUserInfo = wxUserInfoService.getById(noteComment.getUserId());
            noteComment.setWxUserInfo(wxUserInfo);
        });
        return R.ok().put("data", list);
    }

    /**
     * 添加评论
     */
    @PostMapping("/comment")
    public R comment(@RequestBody NoteComment comment) {
        // 检查是否已评论
        QueryWrapper<NoteComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("noteId", comment.getNoteId())
                   .eq("userId", comment.getUserId());
        if (noteCommentService.count(queryWrapper) > 0) {
            return R.error("您已经评论过了");
        }
        
        comment.setCreateTime(new Date());
        noteCommentService.save(comment);
        
        // 更新评论数
        Note note = noteService.getById(comment.getNoteId());
        note.setComments(note.getComments() + 1);
        noteService.updateById(note);
        
        return R.ok();
    }

    /**
     * 检查是否已评论
     */
    @GetMapping("/hasCommented")
    public R hasCommented(@RequestParam Integer noteId,
                         @RequestParam String userId) {
        QueryWrapper<NoteComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("noteId", noteId)
                   .eq("userId", userId);
        return R.ok().put("data", noteCommentService.count(queryWrapper) > 0);
    }

    /**
     * 删除笔记
     */
    @PostMapping("/delete/{id}")
    public R delete(@PathVariable Integer id) {
        Note note = noteService.getById(id);
        if (note == null) {
            return R.error("笔记不存在");
        }
        note.setStatus(1); // 设置为删除状态
        noteService.updateById(note);
        return R.ok();
    }

    /**
     * 恢复笔记
     */
    @PostMapping("/restore/{id}")
    public R restore(@PathVariable Integer id) {
        Note note = noteService.getById(id);
        if (note == null) {
            return R.error("笔记不存在");
        }
        note.setStatus(0); // 设置为正常状态
        noteService.updateById(note);
        return R.ok();
    }

    /**
     * 添加笔记
     */
    @PostMapping("/add")
    public R add(@RequestBody Note note) {
        note.setCreateTime(new Date());
        note.setViews(0);
        note.setComments(0);
        note.setStatus(0);  // 0表示正常状态
        
        boolean success = noteService.save(note);
        if (success) {
            return R.ok();
        } else {
            return R.error("添加失败");
        }
    }

    /**
     * 更新笔记
     */
    @PostMapping("/update")
    public R update(@RequestBody Note note) {
        Note existNote = noteService.getById(note.getId());
        if (existNote == null) {
            return R.error("笔记不存在");
        }
        
        boolean success = noteService.updateById(note);
        if (success) {
            return R.ok();
        } else {
            return R.error("更新失败");
        }
    }

    /**
     * 添加评论
     */
    @PostMapping("/comment/add")
    public R addComment(@RequestBody NoteComment comment) {
        // 设置创建时间
        comment.setCreateTime(new Date());
        
        // 保存评论
        noteCommentService.save(comment);
        
        // 更新笔记评论数
        Note note = noteService.getById(comment.getNoteId());
        note.setComments(note.getComments() + 1);
        noteService.updateById(note);
        
        return R.ok();
    }

    @GetMapping("/analysis")
    public R getNoteAnalysis() {
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 获取总笔记数
            long totalNotes = noteService.count();
            data.put("totalNotes", totalNotes);
            
            // 获取本月新增笔记数
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date startOfMonth = calendar.getTime();
            
            long monthlyNotes = noteService.count(new QueryWrapper<Note>()
                .ge("createTime", startOfMonth));
            data.put("monthlyNotes", monthlyNotes);
            
            // 获取总浏览量
            long totalViews = noteService.list().stream()
                .mapToLong(Note::getViews)
                .sum();
            data.put("totalViews", totalViews);
            
            // 获取近30天的发布趋势
            List<Map<String, Object>> trendData = new ArrayList<>();
            calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -30);
            Date thirtyDaysAgo = calendar.getTime();
            
            List<Note> recentNotes = noteService.list(new QueryWrapper<Note>()
                .ge("createTime", thirtyDaysAgo)
                .orderByAsc("createTime"));
                
            // 使用 SimpleDateFormat 处理日期格式化
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Map<String, Long> dailyCounts = recentNotes.stream()
                .collect(Collectors.groupingBy(
                    note -> dateFormat.format(note.getCreateTime()),
                    Collectors.counting()
                ));
                
            // 填充所有日期，包括没有数据的日期
            calendar = Calendar.getInstance();
            for (int i = 0; i < 30; i++) {
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                String date = dateFormat.format(calendar.getTime());
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", date);
                dayData.put("count", dailyCounts.getOrDefault(date, 0L));
                trendData.add(0, dayData); // 添加到开头，自动按时间正序
            }
            data.put("trendData", trendData);
            
            // 获取浏览量排行TOP10
            List<Map<String, Object>> rankData = noteService.list(new QueryWrapper<Note>()
                .orderByDesc("views")
                .last("LIMIT 10"))
                .stream()
                .map(note -> {
                    Map<String, Object> rankItem = new HashMap<>();
                    rankItem.put("title", note.getTitle());
                    rankItem.put("views", note.getViews());
                    return rankItem;
                })
                .collect(Collectors.toList());
            data.put("rankData", rankData);
            
            return R.ok().put("data", data);
        } catch (Exception e) {
            log.error("获取笔记分析数据失败", e);
            return R.error("获取分析数据失败");
        }
    }
} 